package com.lesso.lll.sunflower.attendance.service.imp;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lesso.lll.sunflower.attendance.entity.AttendanceRule;
import com.lesso.lll.sunflower.attendance.repository.AttendanceRuleRepository;
import com.lesso.lll.sunflower.attendance.service.AttendanceRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 考勤规则服务实现类
 */
@Service
public class AttendanceRuleServiceImpl extends ServiceImpl<AttendanceRuleRepository, AttendanceRule> implements AttendanceRuleService {

    @Autowired
    private AttendanceRuleRepository ruleRepository;

    @Override
    @Transactional
    public Long addRule(AttendanceRule rule) {
        // 检查规则名称是否已存在
        AttendanceRule existRule = ruleRepository.selectByRuleName(rule.getRuleName());
        if (existRule != null) {
            throw new BusinessException("规则名称已存在");
        }

        // 设置默认值
        if (rule.getLateThreshold() == null) {
            rule.setLateThreshold(15); // 默认迟到阈值15分钟
        }
        if (rule.getEarlyLeaveThreshold() == null) {
            rule.setEarlyLeaveThreshold(15); // 默认早退阈值15分钟
        }

        rule.setCreateTime(new Date());
        rule.setUpdateTime(new Date());

        // 保存规则信息
        int result = ruleRepository.insert(rule);
        if (result > 0) {
            return rule.getId();
        }
        return null;
    }

    @Override
    @Transactional
    public boolean updateRule(AttendanceRule rule) {
        if (rule.getId() == null) {
            throw new BusinessException("规则ID不能为空");
        }

        // 更新规则信息
        rule.setUpdateTime(new Date());
        int result = ruleRepository.updateById(rule);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean deleteRule(Long ruleId) {
        // 检查规则是否存在
        AttendanceRule rule = ruleRepository.selectById(ruleId);
        if (rule == null) {
            throw new BusinessException("规则不存在");
        }

        // 删除规则
        int result = ruleRepository.deleteById(ruleId);
        return result > 0;
    }
}    